<?php
namespace User\Model;

use Base\Model\BaseTable;

class UserTable extends BaseTable{

    public function fetchAll($page = null) {
        $this->tableSelect->where('user_owner != 0');
        $this->tableSelect->order('user_id DESC');
        $rowsData = $this->getPaginator($page);
        return $rowsData;
    }

    public function fetchOwnUserWithoutGroup($uid, $page = null) {
        $uid  = (int)$uid;
        $this->tableSelect->columns(array('user_id', 'user_name', 'user_lang', 'user_group', 'user_company'));
        $this->tableSelect->where('user_owner='.$uid);
        $this->tableSelect->where('user_group=0');
        $this->tableSelect->order('user_id DESC');
        $rowsData = $this->getPaginator($page);
        return $rowsData;
    }

    public function getUserById($uid) {
        $uid  = (int)$uid;
        $rowset = $this->tableGateway->select(array('user_id' => $uid));
        $row = $rowset->current();
        return $row;
    }

    public function getUserByName($uname) {
        $rowset = $this->tableGateway->select(array('user_name' => $uname));
        $row = $rowset->current();
        return $row;
    }

    public function countUserByName($uname) {
        $rowset = $this->tableGateway->select(array('user_name' => $uname));
        $rowNumber = $rowset->count();
        return $rowNumber;
    }

    public function saveUser(User $user) {
        $data = array(
            'user_name' => $user->user_name,
            'password' => $user->password,
            'user_lang' => $user->user_lang,
            'user_status' => $user->user_status,
            'user_type' => $user->user_type,
            'user_owner' => $user->user_owner,
            'user_group' => $user->user_group,
            'user_company' => $user->user_company,
            'create_time' => $user->create_time,
        );

        $id = (int)$user->user_id;
        if ($id == 0) {
            $this->tableGateway->insert($data);
            return $this->tableGateway->adapter->getDriver()->getConnection()->getLastGeneratedValue('user_user_id_seq');
//            $id = $this->tableGateway->getLastInsertValue();
        } else {
            if ($row = $this->getUserById($id)) {
                if ($data['password']) {
                    return $this->tableGateway->update(array('password'=>$data['password'], 'user_lang'=>$data['user_lang'], 'user_status'=>$data['user_status']), array('user_id' => $id));
                } else {
                    return $this->tableGateway->update(array('user_lang'=>$data['user_lang'], 'user_status'=>$data['user_status']), array('user_id' => $id));
                }
            } else {
                return false;
            }
        }
    }

    public function deleteUser($id) {
        $id  = (int)$id;
        $this->tableGateway->delete(array('user_id' => $id));
    }
}